package com.springboot_blog.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;

/**
 * JWT工具类
 */
@Slf4j
@Component
public class JwtUtil {

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private Long expiration;

    @Value("${jwt.refresh-expiration}")
    private Long refreshExpiration;

    // 生成签名密钥（0.12.x 推荐方式）
    private SecretKey getSecretKey() {
        // 注意：secret长度需至少32位，否则会抛异常
        return Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
    }

    // 生成访问令牌
    public String generateToken(String username, Map<String, Object> claims) {
        return createToken(username, claims, expiration);
    }

    // 生成刷新令牌
    public String generateRefreshToken(String username) {
        return createToken(username, null, refreshExpiration);
    }

    // 创建令牌核心方法
    private String createToken(String subject, Map<String, Object> claims, Long expirationSeconds) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + expirationSeconds * 1000);

        // 0.12.x 版本构建器用法
        var builder = Jwts.builder()
                .subject(subject)
                .issuedAt(now)
                .expiration(expiryDate)
                .signWith(getSecretKey(), SignatureAlgorithm.HS256);

        if (claims != null && !claims.isEmpty()) {
            builder.claims(claims); // 0.12.x 中 setClaims 已改为 claims()
        }

        return builder.compact();
    }

    // 从令牌中获取用户名
    public String getUsernameFromToken(String token) {
        try {
            return getClaimsFromToken(token).getSubject();
        } catch (Exception e) {
            log.error("获取用户名失败: {}", e.getMessage());
            return null;
        }
    }

    // 从令牌中获取声明（0.12.x 版本写法）
    public Claims getClaimsFromToken(String token) {
        return Jwts.parser()
                .verifyWith(getSecretKey()) // 0.12.x 新增的 verifyWith 方法
                .build()
                .parseSignedClaims(token) // 0.12.x 中 parseClaimsJws 已改为 parseSignedClaims
                .getPayload();
    }

    // 检查令牌是否过期
    public boolean isTokenExpired(String token) {
        try {
            Date expiration = getClaimsFromToken(token).getExpiration();
            return expiration != null && expiration.before(new Date());
        } catch (Exception e) {
            log.error("检查令牌过期失败: {}", e.getMessage());
            return true;
        }
    }

    // 验证令牌
    public boolean validateToken(String token, String username) {
        try {
            String tokenUsername = getUsernameFromToken(token);
            return tokenUsername != null
                    && tokenUsername.equals(username)
                    && !isTokenExpired(token);
        } catch (Exception e) {
            log.error("验证令牌失败: {}", e.getMessage());
            return false;
        }
    }

    // 验证令牌格式
    public boolean isValidToken(String token) {
        try {
            Jwts.parser()
                    .verifyWith(getSecretKey())
                    .build()
                    .parseSignedClaims(token);
            return true;
        } catch (JwtException | IllegalArgumentException e) {
            log.error("令牌无效: {}", e.getMessage());
            return false;
        }
    }

    // 从请求头提取令牌
    public String extractTokenFromHeader(String authHeader) {
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7);
        }
        return null;
    }
}
